/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ilookinto.util;

import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jcr.Repository;
import org.apache.commons.io.IOUtils;
import javax.sql.DataSource;
import org.apache.jackrabbit.core.RepositoryImpl;
import org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager;
import org.apache.jackrabbit.core.version.InternalVersionManagerImpl;

/**
 *
 * @author admin
 */
public class RepDbUtil {

    //
    PrintStream out = System.out;

    static DataSource ds;
    public synchronized DataSource getDataSource(Repository rep) {
        if (ds != null) return ds;
        try {
            RepositoryImpl repi = (RepositoryImpl) rep;
            java.lang.reflect.Method method = RepositoryImpl.class.getDeclaredMethod("getVersionManager");
            method.setAccessible(true);
            InternalVersionManagerImpl vm = (InternalVersionManagerImpl) method.invoke(repi);
            BundleDbPersistenceManager pm = (BundleDbPersistenceManager) vm.getPersistenceManager();
            method = BundleDbPersistenceManager.class.getDeclaredMethod("getDataSource");
            method.setAccessible(true);
            ds = (javax.sql.DataSource) method.invoke(pm);
            return ds;
        } catch (Exception e) {
            return null;
        }
    }

    public Map getTags(String user,  Repository rep, String... uuids)
    {
         Map<String, List> map = new HashMap<String, List>();
         DataSource ds = this.getDataSource(rep);
        Connection con = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            con = ds.getConnection();
            String tagsql = "SELECT t.name FROM bookmark bm, bookmark_tags bt, tags t where uuid = ? "  +
                        " AND bm.id = bt.bookmark_id AND bt.id = t.tag_id";
            st = con.prepareStatement(tagsql);
            for (String uuid: uuids)  {
                st.setString(1, uuid);
                rs = st.executeQuery();
                List<String> tagList = new ArrayList<String>();
                while (rs.next())
                {
                  tagList.add(rs.getString(1));
                }
                map.put(uuid, tagList);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            CloseUtil.close(rs, st, con);
        }
         return map;
    }
    public void insert(String tags, String guid, Repository rep) {
        DataSource ds = this.getDataSource(rep);
        Connection con = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            con = ds.getConnection();
             String checkbm = "SELECT * FROM bookmark where uuid = ?";
            st = con.prepareStatement(checkbm);
            if (!st.executeQuery().next()) {
                st.close();
                st = con.prepareStatement("INSERT INTO bookmark VALUES (0, 'public', ?, 'desc')");
                st.setString(1, guid);
                st.execute();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            CloseUtil.close(rs, st, con);
        }

    }

    String creatTagSchema() {
        //this.getClass().getResourceAsStream("tag-derby.sql");
        String sql = "";
        try {
            sql = IOUtils.toString(this.getClass().getResourceAsStream("tag-derby.sql"));
            out.println(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sql;
    }

   /* void test() throws Exception {
        java.sql.Connection con = ds.getConnection();
        java.sql.Statement statement = con.createStatement();
        java.sql.DatabaseMetaData dm = con.getMetaData();
        java.sql.ResultSet rs = dm.getTables(null, null, "TAGS", null);
        if (rs.next()) {
            out.println("exists");
        } else {
            statement.execute("Create Table tags (guid varchar(20), tag varchar(50))");
        }
        rs.close();
        statement.execute("insert into tags values ('1', 'mytag')");

        rs = statement.executeQuery("SELECT * from TAGS");
        while (rs.next()) {
            out.println(rs.getString(1) + "..." + rs.getString(2));
        }
        con.close();
    }*/

    public static void main(String s[]) {
        new RepDbUtil().creatTagSchema();
    }
}
